import { ModalForm, ProFormSelect, ProFormSwitch } from '@ant-design/pro-components';
import { Calendar, message } from 'antd';
import * as moment from 'moment';
import { useEffect, useState } from 'react';
import { createSchedule, getShifts, removeSchedule } from '../../service';
import { getStaffMonthSchedule, queryParkinglotNamesForSchedule } from '../service';
import { DayScheduleItem, TollCollectorTableItem } from '../types.d';
import type { CreateScheduleType } from '../../types.d';
import ScheduleItem from './ScheduleItem';
import CopySchedule from './CopySchedule';
import { WarningFilled } from '@ant-design/icons';

const ConfigSchedule = (props: {
  staffInfo: TollCollectorTableItem;
  calendarVisible: boolean;
  close: () => void;
}) => {
  const { staffInfo, calendarVisible, close } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [delVisible, setDelVisible] = useState<boolean>(false);
  const [selectDay, setSelectDay] = useState('');
  const [staffSchedule, setStaffSchedule] = useState<{ [key: string]: DayScheduleItem }>();
  const [currItem, setCurrItem] = useState<DayScheduleItem>();
  const [allPk, setAllPk] = useState<boolean>(false);
  const [currShowMonth, setCurrShowMonth] = useState<string>(moment().format('YYYY-MM-DD'));
  const refreshSchedule = async (m?: number, y?: number) => {
    const year = y || moment().year();
    const month = m == undefined ? moment().month() : m;
    const res = await getStaffMonthSchedule({ year, month, jobNo: staffInfo.jobNo });
    const mapObj: Record<string, any> = {};
    res.forEach((item) => {
      mapObj[item.day] = item;
    });
    setStaffSchedule(() => mapObj);
  };
  useEffect(() => {
    refreshSchedule();
  }, []);
  let canUserClick = true;
  return (
    <ModalForm
      title={
        <div>
          工作排班 - {staffInfo.name}({staffInfo.jobNo}){' '}
          <CopySchedule
            ownerId={staffInfo.ownerId}
            jobNo={staffInfo.jobNo}
            userName={staffInfo.name}
            showSchduleDay={currShowMonth}
          />
        </div>
      }
      width="85vw"
      visible={calendarVisible}
      modalProps={{
        style: {
          minWidth: '800px',
        },
        destroyOnClose: true,
        maskClosable: false,
        onCancel: () => {
          close();
        },
      }}
      submitter={false}
    >
      <Calendar
        mode="month"
        disabledDate={(date) => {
          return date.valueOf() <= moment().startOf('D').valueOf();
        }}
        dateCellRender={(value: moment.Moment) => {
          if (!staffSchedule) return;
          const dayItem = staffSchedule[value.format('YYYY-MM-DD')];
          if (!dayItem) return;
          return (
            <ScheduleItem
              item={dayItem}
              editClick={() => {
                setCurrItem(dayItem);
                setAllPk(dayItem.allParkValid || false);
                setVisible(true);
              }}
              removeClick={() => {
                setCurrItem(dayItem);
                setDelVisible(true);
              }}
            />
          );
        }}
        onPanelChange={(value) => {
          canUserClick = false;
          setCurrShowMonth(`${value.year()}-${value.month() + 1}-01`);
          refreshSchedule(value.month(), value.year());
        }}
        validRange={[moment().startOf('D'), moment().add(1, 'M').endOf('M')]}
        onSelect={(value: moment.Moment) => {
          if (canUserClick) {
            const sd = value.format('YYYY-MM-DD');
            setSelectDay(sd);

            if (!staffSchedule || !staffSchedule[sd]) {
              setCurrItem(undefined);
              setAllPk(false);
              setVisible(true);
            }
          }
        }}
      />
      <ModalForm<CreateScheduleType>
        layout="horizontal"
        width="40vw"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setSelectDay('');
            setAllPk(false);
            setVisible(false);
          },
        }}
        title={`当前排班日期: ${selectDay}`}
        visible={visible}
        onFinish={async (value) => {
          const data2creaet: CreateScheduleType = {
            id: staffInfo._id,
            day: selectDay,
            shiftConfigName: value.shiftConfigName,
            parkingLotIds: value.parkingLotIds,
            allParkValid: value.allParkValid,
          };
          const res = await createSchedule(data2creaet);
          if (!res?.success) {
            message.error({ content: res?.message, key: 'config_schedule' });
            return false;
          }
          message.success({ content: '排班成功', key: 'config_schedule' });
          refreshSchedule(moment(selectDay).month(), moment(selectDay).year());
          setVisible(false);
          return true;
        }}
        initialValues={
          currItem
            ? {
                shiftConfigName: currItem.shiftConfigName,
                parkingLotIds: currItem.parkingLots.map((item) => item.parkingLotId),
                allParkValid: currItem.allParkValid,
              }
            : undefined
        }
      >
        <ProFormSelect
          name="shiftConfigName"
          label="执勤班次"
          debounceTime={300}
          showSearch
          required
          placeholder="请选择用户执勤班次"
          request={(val) => getShifts(val.keyWords, staffInfo.ownerId)}
        />
        <ProFormSwitch
          name="allParkValid"
          label="全部路段"
          fieldProps={{
            onChange: (v) => {
              setAllPk(v);
            },
          }}
        />
        {!allPk && (
          <ProFormSelect
            name="parkingLotIds"
            label="选择路段"
            showSearch
            mode="multiple"
            debounceTime={300}
            placeholder="请选择路段"
            rules={[
              {
                required: true,
                message: '请选择路段',
                validator: (_, val) => {
                  if (!val || val.length < 1) {
                    return Promise.reject(new Error('执勤路段不可为空'));
                  }
                  if (val && val.length <= 20) {
                    return Promise.resolve(val);
                  }
                  return Promise.reject(new Error('执勤路段最多选择20个'));
                },
              },
            ]}
            request={(val) =>
              queryParkinglotNamesForSchedule(
                val.keyWords,
                staffInfo.ownerId,
                currItem?.parkingLots?.map((item) => ({
                  label: item.parkingLotName,
                  value: item.parkingLotId,
                })),
              )
            }
          />
        )}
      </ModalForm>
      {currItem && delVisible && (
        <ModalForm
          title={
            <>
              <WarningFilled
                style={{
                  color: 'red',
                  marginRight: '5px',
                }}
              />
              删除警告
            </>
          }
          width="35vw"
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setSelectDay('');
              setDelVisible(false);
              setCurrItem(undefined);
            },
          }}
          visible={delVisible}
          submitter={{
            submitButtonProps: {
              danger: true,
            },
          }}
          onFinish={async () => {
            const res = await removeSchedule(currItem._id);
            if (res.success) {
              refreshSchedule(moment(selectDay).month(), moment(selectDay).year());
              message.success({ content: res.message, key: 'delete_key' });
              setDelVisible(false);
              setCurrItem(undefined);
              return true;
            }
            message.error({ content: res.message, key: 'delete_key' });
            return false;
          }}
        >
          <div>是否确认删除{selectDay}的排班？</div>
        </ModalForm>
      )}
    </ModalForm>
  );
};

export default ConfigSchedule;
